package com.mystudy.copy;

import org.junit.Test;

import java.io.*;

/**
 * @program: infoalgorithm
 * @description: 深度拷贝
 * @author: zhouzhilong
 * @create: 2019-07-10 14:23
 **/
public class DeepCopy {

    @Test
    public void test() throws IOException, ClassNotFoundException {

        Age a = new Age(20);
        Student zhangshan = new Student("张三", a, 10);
        //通过序列化方法实现深拷贝
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(output);
        oos.writeObject(zhangshan);
        oos.flush();
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(output.toByteArray()));
        Student zhangsan2 = (Student) ois.readObject();
        System.out.println(zhangshan.toString());
        System.out.println(zhangsan2.toString());

        System.out.println();

        //修改１号对象的属性
        zhangshan.setName("李四");
        //修改age这个引用类型的成员变量的值
        a.setAge(99);
        zhangshan.setLength(333);
        System.out.println(zhangshan.toString());
        System.out.println(zhangsan2.toString());


    }




    static class Age implements Serializable{
        private int age;

        public Age(int age) {
            this.age = age;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "Age{" +
                    "age=" + age +
                    '}';
        }
    }

    static class Student implements Serializable {
        private String name;
        private Age age;
        private int length;

        public Student(String name, Age age, int length) {
            this.name = name;
            this.age = age;
            this.length = length;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Age getAge() {
            return age;
        }

        public void setAge(Age age) {
            this.age = age;
        }

        public int getLength() {
            return length;
        }

        public void setLength(int length) {
            this.length = length;
        }


        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", age=" + age.toString() +
                    ", length=" + length +
                    '}';
        }
    }
}
